<template>
	<view>
		<!-- 患者列表 -->
		<view class="cell-box" v-for="(item, index) in clients" :key="index">
			<view class="weui-cell" @click="onClientSelected" :data-index="index">
				<view class="weui-cell__bd">
					<view>
						<text style="font-weight: bold">{{ item.patientName }}</text>
					</view>
					<view>
						<text :class="'sext' + item.sex">性别：{{ item.sex == 1 ? '男' : '女' }}</text>
						<text style="margin-left: 10rpx">年龄：{{ item.age }} 岁</text>
						<text style="margin-left: 10rpx">联系电话：{{ item.patientPhone }}</text>
						<text style="margin-left: 10rpx">详细地址：{{ item.address }}</text>
					</view>
				</view>
				<view class="weui-cell__ft">
					<text v-if="act == 'select'" style="
		                display: inline-block;
		                padding: 15rpx 30rpx;
		                border: 1rpx solid #0bb584;
		                color: #0bb584;
		                font-weight: bold;
		                border-radius: 10rpx;
		                font-size: 28rpx;
		                overflow: hidden;
		            ">
						选择
					</text>

					<text v-else-if="act == 'edit'" @click="removeClient" :data-id="item.id" style="
		                display: inline-block;
		                padding: 15rpx 30rpx;
		                border: 1rpx solid #eeeeee;
		                color: #f13e6d;
		                border-radius: 10rpx;
		                font-size: 28rpx;
		                overflow: hidden;
		            ">
						删除
					</text>
				</view>
			</view>
		</view>

		<!-- 固定新增按钮 -->
		<view class="fixed-add-button" @click="showAddModal" v-if="!isAddModalVisible">
			<text style="
			    display: inline-block;
			    padding: 15rpx 30rpx;
			    background-color: #0bb584;
			    color: white;
			    font-weight: bold;
			    border-radius: 10rpx;
			    font-size: 28rpx;
			    overflow: hidden;
			">
				新增
			</text>
		</view>

		<!-- 新增患者的模态框 -->
		<uni-popup ref="addPopup" type="center" @change="handlePopupChange">
			<view class="popup-content">
				<view class="popup-title">新增患者信息</view>
				<form @submit.prevent="addClientSubmit">
					<view class="form-item">
						<label>姓名:</label>
						<input v-model="newPatient.patientName" placeholder="请输入姓名" />
						<text v-if="validationErrors.patientName"
							class="error-message">{{ validationErrors.patientName }}</text>
					</view>
					<view class="form-item">
						<label>性别:</label>
						<picker mode="selector" :range="sexOptions" range-key="name" @change="bindSexChange">
							<view>{{ sexOptions[sexIndex].name }}</view>
						</picker>
						<text v-if="validationErrors.sex" class="error-message">{{ validationErrors.sex }}</text>
					</view>
					<view class="form-item">
						<label>年龄:</label>
						<input v-model="newPatient.age" placeholder="请输入年龄" type="number" />
						<text v-if="validationErrors.age" class="error-message">{{ validationErrors.age }}</text>
					</view>
					<view class="form-item">
						<label>联系电话:</label>
						<input v-model="newPatient.patientPhone" placeholder="请输入联系电话" />
						<text v-if="validationErrors.patientPhone"
							class="error-message">{{ validationErrors.patientPhone }}</text>
					</view>
					<view class="form-item">
						<label>详细地址:</label>
						<textarea v-model="newPatient.address" placeholder="请输入详细地址"></textarea>
						<text v-if="validationErrors.address"
							class="error-message">{{ validationErrors.address }}</text>
					</view>
					<button form-type="submit" :disabled="hasValidationErrors">保存</button>
				</form>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		computed
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const app = getApp()
	const act = ref('')
	const clients = ref([])
	const token = uni.getStorageSync('token');
	const addPopup = ref(null);
	const newPatient = reactive({
		patientName: '',
		sex: -1,
		age: null,
		patientPhone: '',
		address: ''
	});
	const sexOptions = [{
			name: '请选择性别',
			value: -1
		},
		{
			name: '男',
			value: 1
		},
		{
			name: '女',
			value: 2
		}
	];
	const sexIndex = ref(0);
	const isAddModalVisible = ref(false);

	const validationErrors = reactive({
		patientName: '',
		sex: '',
		age: '',
		patientPhone: '',
		address: ''
	});

	const hasValidationErrors = computed(() => {
		return Object.values(validationErrors).some(error => error !== '');
	});

	onLoad((options) => {
		act.value = options.act
		console.log('就诊人options', options);
		if (options.act === 'select') {
			uni.setNavigationBarTitle({
				title: '请选择就诊人'
			})
		} else if (options.act === 'edit') {
			uni.setNavigationBarTitle({
				title: '就诊人信息'
			})
		} else {
			uni.setNavigationBarTitle({
				title: '就诊人信息'
			})
		};
		fetchClients();
	})

	const fetchClients = () => {
		console.log('开始请求患者列表');
		app.globalData.utils.myrequest({
			myurl: '/patientInfo/list',
			header: {
				'Authorization': token,
				'Source-Platform': 'mini-program'
			},
			mysuccess: (res) => {
				console.log('就诊人信息', res.data);
				if (Array.isArray(res.data)) {
					clients.value = res.data;
				} else {
					console.error('响应数据不是数组', res.data);
				}
			},
			myfail: (error) => {
				console.error('就诊人列表接口调用失败', error);
			}
		})
	}

	const onClientSelected = (e) => {
		console.log('selectmaninfo', e);
		uni.$emit('changeClient', clients.value[e.currentTarget.dataset.index])
		uni.navigateBack()
	}

	const removeClient = (e) => {
		const id = e.currentTarget.dataset.id;
		console.log('删除患者ID:', id);
		// 删除逻辑
		app.globalData.utils.myrequest({
			myurl: '/patientInfo/delete',
			method: 'DELETE',
			data: {
				id: id
			},
			header: {
				'Authorization': token,
				'Source-Platform': 'mini-program'
			},
			mysuccess: (res) => {
				console.log('删除成功', res.data);
				fetchClients(); // 刷新列表
			},
			myfail: (error) => {
				console.error('删除失败', error);
			}
		})
	}

	const showAddModal = () => {
		if (addPopup.value) {
			isAddModalVisible.value = true;
			addPopup.value.open();
		} else {
			console.error('addPopup ref is not properly set up');
		}
	}

	const bindSexChange = (e) => {
		sexIndex.value = e.detail.value;
		newPatient.sex = sexOptions[sexIndex.value].value;
	}

	const validateForm = () => {
		let isValid = true;

		if (!newPatient.patientName.trim()) {
			validationErrors.patientName = '姓名不能为空';
			isValid = false;
		} else {
			validationErrors.patientName = '';
		}

		if (newPatient.sex <= 0) {
			validationErrors.sex = '请选择性别';
			isValid = false;
		} else {
			validationErrors.sex = '';
		}

		if (!newPatient.age || newPatient.age <= 0) {
			validationErrors.age = '年龄必须大于0';
			isValid = false;
		} else {
			validationErrors.age = '';
		}

		if (!newPatient.patientPhone.trim()) {
			validationErrors.patientPhone = '联系电话不能为空';
			isValid = false;
		} else {
			validationErrors.patientPhone = '';
		}

		if (!newPatient.address.trim()) {
			validationErrors.address = '详细地址不能为空';
			isValid = false;
		} else {
			validationErrors.address = '';
		}

		return isValid;
	}

	const addClientSubmit = () => {
		if (validateForm()) {
			console.log('新增患者数据:', newPatient);
			app.globalData.utils.myrequest({
				myurl: '/patientInfo/save',
				method: 'POST',
				data: newPatient,
				header: {
					'Authorization': token,
					'Source-Platform': 'mini-program'
				},
				mysuccess: (res) => {
					console.log('新增成功', res.data);
					fetchClients(); // 刷新列表
					addPopup.value.close();
					resetNewPatient();
				},
				myfail: (error) => {
					console.error('新增失败', error);
				}
			})
		}
	}

	const resetNewPatient = () => {
		newPatient.patientName = '';
		newPatient.sex = -1;
		newPatient.age = null;
		newPatient.patientPhone = '';
		newPatient.address = '';
		sexIndex.value = 0;
		for (const key in validationErrors) {
			validationErrors[key] = '';
		}
	}

	const handlePopupChange = (status) => {
		if (!status.show) {
			isAddModalVisible.value = false;
			resetNewPatient();
		}
	}
</script>

<style>
	/* 添加一些基本样式 */
	.cell-box {
		margin-bottom: 20rpx;
	}

	.weui-cell {
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.weui-cell__bd text {
		display: block;
		margin-bottom: 10rpx;
	}

	.fixed-add-button {
		position: fixed;
		bottom: 30rpx;
		right: 30rpx;
		z-index: 999;
	}

	.popup-content {
		background-color: white;
		padding: 30rpx;
		border-radius: 10rpx;
		width: 600rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		text-align: center;
	}

	.form-item {
		margin-bottom: 20rpx;
	}

	.form-item label {
		display: block;
		margin-bottom: 10rpx;
		font-weight: bold;
	}

	.form-item input,
	.form-item textarea {
		border: 1rpx solid #ccc;
		padding: 10rpx;
		border-radius: 5rpx;
		width: 100%;
		box-sizing: border-box;
	}

	button {
		background-color: #0bb584;
		color: white;
		border: none;
		padding: 15rpx 30rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
		cursor: pointer;
		display: block;
		margin: 0 auto;
	}

	.error-message {
		color: red;
		font-size: 24rpx;
		margin-top: 10rpx;
	}
</style>